<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户管理</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script src="/js/jquery.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <style>
        body { margin: 0; padding: 0; background: #f5f6fa; display: flex; min-height: 100vh; }
        .main-wrapper {
            display: flex;
            width: 100%;
        }
        .sidebar {
            width: 240px;
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            padding: 0;
            box-shadow: 2px 0 8px rgba(0,0,0,0.07);
            min-height: 100vh;
            color: #fff;
            display: flex;
            flex-direction: column;
            align-items: stretch;
        }
        .sidebar h3 {
            color: #fff;
            font-weight: bold;
            text-align: center;
            padding: 32px 0 16px 0;
            letter-spacing: 2px;
            font-size: 1.3rem;
            margin-bottom: 0;
        }
        .sidebar ul {
            list-style: none;
            padding: 0 0 32px 0;
            margin: 0;
            flex: 1;
        }
        .sidebar ul li {
            margin: 0;
        }
        .sidebar ul li a {
            display: flex;
            align-items: center;
            padding: 14px 32px;
            color: #e3e6f0;
            text-decoration: none;
            font-size: 1.08rem;
            border-left: 4px solid transparent;
            transition: background 0.2s, color 0.2s, border-color 0.2s;
            border-radius: 0 24px 24px 0;
            margin-bottom: 2px;
        }
        .sidebar ul li a:hover,
        .sidebar ul li a.active {
            background: rgba(255,255,255,0.12);
            color: #fff;
            border-left: 4px solid #f6c23e;
            font-weight: bold;
        }
        .sidebar ul li a .icon {
            margin-right: 10px;
            font-size: 1.2em;
        }
        .main-content {
            flex-grow: 1; /* Allow main content to take up remaining space */
            padding: 20px;
            background-color: #f5f6fa; /* Light grey background for main content area */
        }
        .info-card {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px; /* Add some space below the card */
        }
        .form-group label { font-weight: bold; }
        /* Adjust table styling if needed */
        .table thead th { background-color: #e9ecef; }
        
        /* 模态框头像样式 */
        #modalAvatarPreview img {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
        }
        #modalAvatarUpload {
            width: 80px;
            height: 80px;
            border: 2px dashed #ccc;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-size: 24px;
            color: #666;
        }
    </style>
</head>
<body>

<div class="main-wrapper">
    <div class="sidebar">
        <h3>医院病例管理系统</h3>
        <ul>
<%--            <li><a href="/adminStatistics">统计分析</a></li>--%>
            <li><a href="/adminUserList" class="active">用户管理</a></li>
            <li><a href="/adminMedicalRecordList">病历管理</a></li>
            <li><a href="/adminPersonalCenter">个人信息管理</a></li>
            <li><a href="/adminMedicalTemplate">病历模板管理</a></li>
            <li><a href="/adminUpdateRequest">信息修改申请</a></li>
        </ul>
    </div>
    <div class="main-content">
        <div class="info-card">
            <h2>用户列表</h2>
            <%-- Add search/filter controls here if needed --%>
            <div class="mb-3">
                <input type="text" id="userSearchInput" class="form-control" placeholder="输入用户名或昵称搜索">
            </div>
            <table class="table table-striped">
                <thead>
                <tr>
                    <th>头像</th>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>昵称</th>
                    <th>角色</th>
                    <th>性别</th>
                    <th>年龄</th>
                    <th>邮箱</th>
                    <th>手机</th>
                    <th>创建时间</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="userTableBody">
                <%-- 用户数据将在这里加载 --%>
                </tbody>
            </table>
            <div id="loading" class="text-center">加载中...</div>
            <div id="error" class="alert alert-danger" style="display: none;">加载失败</div>
        </div>
    </div>
</div>

<script>
    $(function(){
        // 获取用户列表数据
        function loadUsers() {
            $('#loading').show();
            $('#error').hide();
            const searchTerm = $('#userSearchInput').val(); // Get search term

            $.ajax({
                url: '/admin/users/list',
                type: 'GET',
                // Pass search term if your backend supports filtering
                // data: { searchTerm: searchTerm },
                success: function(res){
                    $('#loading').hide();
                    if(res.code === 0 && res.data){
                        let users = res.data;
                        const $tbody = $('#userTableBody');
                        $tbody.empty(); // 清空现有数据

                        // Client-side filtering (if backend doesn't support)
                        if (searchTerm) {
                            const lowerSearchTerm = searchTerm.toLowerCase();
                            users = users.filter(user =>
                                (user.username && user.username.toLowerCase().includes(lowerSearchTerm)) ||
                                (user.nickname && user.nickname.toLowerCase().includes(lowerSearchTerm))
                            );
                        }

                        if (users.length === 0) {
                            $tbody.append('<tr><td colspan="10" class="text-center">无匹配用户</td></tr>');
                            return;
                        }

                        users.forEach(user => {
                            const role = user.role === 1 ? '管理员' : '患者';
                            const genderDisplay = user.gender === 0 ? '男' : '女';

                            const $row = $('<tr>');
                            // 添加头像列 (第一列)
                            const $avatarCell = $('<td>');
                            if (user.avatar) {
                                const $avatarImg = $('<img>')
                                    .attr('src', user.avatar)
                                    .attr('alt', '头像')
                                    .css({'width': '30px', 'height': '30px', 'border-radius': '50%', 'object-fit': 'cover'}); // 添加样式
                                $avatarCell.append($avatarImg);
                            } else {
                                $avatarCell.text('无头像'); // 没有头像时显示文本
                            }
                            $row.append($avatarCell);

                            $row.append($('<td>').text(user.id));
                            $row.append($('<td>').text(user.username));
                            $row.append($('<td>').text(user.nickname || '-'));
                            $row.append($('<td>').text(role));
                            $row.append($('<td>').text(genderDisplay));
                            $row.append($('<td>').text(user.age || '-'));
                            $row.append($('<td>').text(user.email || '-'));
                            $row.append($('<td>').text(user.phone || '-'));

                            $row.append($('<td>').text(new Date(user.createTime).toLocaleString()));

                            const $editButton = $('<button>').addClass('btn btn-sm btn-primary edit-btn').text('编辑').attr('data-id', user.id);
                            const $deleteButton = $('<button>').addClass('btn btn-sm btn-danger delete-btn').text('删除').attr('data-id', user.id);

                            const $actionsCell = $('<td>').append($editButton).append($deleteButton);
                            $row.append($actionsCell);

                            $tbody.append($row);
                        });

                        // 使用事件委托为动态添加的删除按钮绑定点击事件
                        $('#userTableBody').on('click', '.delete-btn', function(){
                            const userId = $(this).data('id');
                            if (confirm('确定要删除此用户吗？')) {
                                deleteUser(userId);
                            }
                        });

                        // 使用事件委托为动态添加的编辑按钮绑定点击事件
                        $('#userTableBody').on('click', '.edit-btn', function(){
                            const userId = $(this).data('id');
                            if (userId) {
                                loadUserDataAndShowModal(userId);
                            } else {
                                alert('无法获取用户ID，请稍后重试。');
                            }
                        });

                    } else {
                        $('#error').text(res.message || '获取用户列表失败').show();
                    }
                },
                error: function(){
                    $('#loading').hide();
                    $('#error').text('请求失败，请稍后重试').show();
                }
            });
        }

        // 删除用户
        function deleteUser(userId) {
            $.ajax({
                url: '/admin/users/delete/' + userId,
                type: 'POST', // Or DELETE, depending on backend implementation
                success: function(res){
                    if(res.code === 0){
                        alert('用户删除成功');
                        loadUsers(); // 刷新列表
                    } else {
                        alert(res.message || '删除失败');
                    }
                },
                error: function(){
                    alert('删除失败，请稍后重试');
                }
            });
        }

        // 加载用户数据并显示编辑模态框
        function loadUserDataAndShowModal(userId) {
            $('#modalUserId').val(userId);
            $('#editUserModalForm')[0].reset(); // 重置表单
            $('#modalAvatarPreview').hide();
            $('#modalAvatarUpload').show();
            $('#modalAvatarUpload').next('small').show();
             $('#modalAvatarPath').val(''); // 清空头像路径
            
            $.ajax({
                url: '/admin/users/' + userId, // 调用根据ID获取用户信息的后端接口
                type: 'GET',
                success: function(res) {
                    if (res.code === 0 && res.data) {
                        const user = res.data;
                        // 填充模态框表单
                        $('#modalUsername').val(user.username);
                        $('#modalUserRole').val(user.role);
                        $('#modalNickname').val(user.nickname || '');
                        $('#modalGender').val(user.gender);
                        $('#modalAge').val(user.age || '');
                        $('#modalPhone').val(user.phone || '');
                        $('#modalEmail').val(user.email || '');
                        $('#modalAvatarPath').val(user.avatar || '');

                        // 显示头像
                        if (user.avatar) {
                            $('#modalAvatarPreview img').attr('src', user.avatar);
                            $('#modalAvatarPreview').show();
                            $('#modalAvatarUpload').hide();
                            $('#modalAvatarUpload').next('small').hide();
                        } else {
                            $('#modalAvatarPreview').hide();
                            $('#modalAvatarUpload').show();
                            $('#modalAvatarUpload').next('small').show();
                        }

                        // 显示模态框
                        const editUserModal = new bootstrap.Modal(document.getElementById('editUserModal'));
                        editUserModal.show();

                    } else {
                        alert('获取用户信息失败: ' + (res.message || ''));
                    }
                },
                error: function() {
                    alert('获取用户信息失败，请稍后重试。');
                }
            });
        }

        // 模态框保存按钮点击事件
        $('#saveUserModalButton').click(function(){
            const userId = $('#modalUserId').val();
            const userData = {
                id: userId,
                nickname: $('#modalNickname').val(),
                phone: $('#modalPhone').val(),
                email: $('#modalEmail').val(),
                age: $('#modalAge').val(),
                gender: $('#modalGender').val(),
                role: $('#modalUserRole').val(),
                avatar: $('#modalAvatarPath').val()
            };

            $.ajax({
                url: '/admin/users/update', // 调用更新用户信息的后端接口
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(userData),
                success: function(res) {
                    if (res.code === 0) {
                        alert('用户信息更新成功');
                        const editUserModal = bootstrap.Modal.getInstance(document.getElementById('editUserModal'));
                        editUserModal.hide(); // 关闭模态框
                        loadUsers(); // 刷新列表
                    } else {
                        alert('用户信息更新失败: ' + (res.message || ''));
                    }
                },
                error: function() {
                    alert('用户信息更新失败，请稍后重试。');
                }
            });
        });

        // 模态框头像上传逻辑 (参考 personalCenter.jsp)
        // 添加隐藏的文件输入框到模态框表单
         $('#editUserModalForm .form-group.col-md-6').has('label[for="modalAvatar"]').append('<input type="file" id="modalAvatarFileInput" accept="image/*" style="display: none;">');

         // 处理模态框头像上传
         $('#modalAvatarFileInput').on('change', function(e) {
             var file = e.target.files[0];
             if (file) {
                 var formData = new FormData();
                 formData.append('file', file);

                 $.ajax({
                     url: '/user/upload/avatar', // 使用用户头像上传接口
                     type: 'POST',
                     data: formData,
                     processData: false,
                     contentType: false,
                     success: function(res) {
                         if(res.code === 0) {
                             $('#modalAvatarPreview img').attr('src', res.data);
                             $('#modalAvatarPreview').show();
                             $('#modalAvatarPath').val(res.data);
                             $('#modalAvatarUpload').hide();
                             $('#modalAvatarUpload').next('small').hide();
                         } else {
                             alert(res.message || '头像上传失败');
                         }
                     },
                     error: function() {
                         alert('头像上传失败，请稍后重试');
                     }
                 });
             }
         });

         // 触发文件选择 (模态框)
         $('#modalAvatarUpload, #modalAvatarPreview').click(function() {
              $('#modalAvatarFileInput').click();
         });

        // 页面加载时获取用户列表
        loadUsers();

        // Add search functionality (basic client-side filtering for now)
        $('#userSearchInput').on('input', loadUsers);
    });
</script>

</body>
</html>

<!-- 编辑用户模态框 -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editUserModalLabel">编辑用户信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <%-- 复用 adminUserEdit.jsp 中的表单结构 --%>
                <form id="editUserModalForm">
                    <input type="hidden" id="modalUserId">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="modalAvatar">头像</label>
                            <div>
                                <%-- Placeholder for avatar image or upload area --%>
                                <div id="modalAvatarPreview" class="avatar-preview" style="display: none;">
                                    <img src="" alt="Avatar">
                                </div>
                                <div id="modalAvatarUpload" class="avatar-upload-area">
                                    +
                                </div>
                                <small class="form-text text-muted">点击上传头像</small>
                            </div>
                        </div>
                        <div class="form-group col-md-6">
                            <input type="hidden" id="modalAvatarPath">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="modalUsername">账号</label>
                            <input type="text" class="form-control" id="modalUsername" readonly>
                        </div>
                        <div class="form-group col-md-6">
                            <label for="modalUserRole">角色</label>
                            <select class="form-control" id="modalUserRole">
                                <option value="0">患者</option>
                                <option value="1">管理员</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="modalNickname">昵称</label>
                            <input type="text" class="form-control" id="modalNickname">
                        </div>
                        <div class="form-group col-md-6">
                            <label for="modalGender">性别</label>
                            <select class="form-control" id="modalGender">
                                <option value="0">男</option>
                                <option value="1">女</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="modalAge">年龄</label>
                            <input type="text" class="form-control" id="modalAge">
                        </div>
                        <div class="form-group col-md-6">
                            <label for="modalPhone">手机号码</label>
                            <input type="text" class="form-control" id="modalPhone">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="modalEmail">邮箱</label>
                            <input type="text" class="form-control" id="modalEmail">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="saveUserModalButton">保存</button>
            </div>
        </div>
    }
</div> 